<?php
// ========================== 提交数据操作 ==========================//

require_once('global.php');

//if($_SERVER['REQUEST_METHOD'] == 'POST' && (empty($_SERVER['HTTP_REFERER']) || $_POST['formhash'] != formhash() || preg_replace("/https?:\/\/([^\:\/]+).*/i", "\\1", $_SERVER['HTTP_REFERER']) !== preg_replace("/([^\:]+).*/", "\\1", $_SERVER['HTTP_HOST']))) {
//	message('您的请求来路不正确,无法提交');
//}

//如果开启伪静态则设置伪静态的页面的URL
//if ($options['rewrite_enable']) {
//	$loginurl = 'login.'.$options['rewrite_ext'];
//	$regurl = 'register.'.$options['rewrite_ext'];
//} else {
	$loginurl = './index.php?action=login';
	$regurl = './index.php?action=register';
//}

if($_POST['action'] == 'registerok' || $_POST['action'] == 'modpro') {
	// 取值并过滤部分
	$doreg = $_POST['action'] == 'registerok' ? true : false;

	$username        = trim($_POST['username']);
	$password        = $_POST['password'];
	$confirmpassword = $_POST['confirmpassword'];
	$email             = trim($_POST['email']);
	$url             = trim($_POST['url']);
	$result = checkurl($email);
	if($result) {
		message($result);
	}
	if ($doreg) {
		//注册
		if ($options['seccode_enable']) {
		$clientcode = $_POST['clientcode'];
		session_start();
		if (!$clientcode || strtolower($clientcode) != strtolower($_SESSION['code'])) {
	    	unset($_SESSION['code']);
	        message("" . _LANG_1112 . "", $regurl);
	        return false;
	    }
	  }
		if(!$username || strlen($username) > 30) {
			message('用户名为空或者超过30字节.', $regurl);
		}

		if ($options['censoruser']) {
			$options['censoruser'] = str_replace('，', ',', $options['censoruser']);
			$banname = explode(',',$options['censoruser']);
			foreach($banname as $value){
				if (strpos($username,$value) !== false){
					message('此用户名包含不可接受字符或被管理员屏蔽,请选择其它用户名.', $regurl);
				}
			}
		}

		$name_key = array("\\",'&',' ',"'",'"','/','*',',','<','>',"\r","\t","\n",'#','$','(',')','%','@','+','?',';','^');
		foreach($name_key as $value){
			if (strpos($username,$value) !== false){
				message('此用户名包含不可接受字符或被管理员屏蔽,请选择其它用户名.', $regurl);
			}
		}
		if (!$password || strlen($password) < 6) {
			message('密码不能为空并且密码长度不能小于6位.',$regurl);
		}
		if ($password != $confirmpassword) {
			message('请确认输入的密码一致.', $regurl);
		}
		if (strpos($newpassword,"\n") !== false || strpos($password,"\r") !== false || strpos($password,"\t") !== false) {
			message('密码包含不可接受字符.', $regurl);
		}
		$username = char_cv($username);
		$r = $db->fetch_one_array("SELECT uid FROM {$tablepre}xna_users WHERE username='$username'");
		if($r['uid']) {
			message('该用户名已被注册,请返回重新选择其他用户名.', $regurl);
			unset($r);
		}
		$url = char_cv($url);
		if ($url && isemail($url)) {
			$r = $db->fetch_one_array("SELECT uid FROM {$tablepre}xna_users WHERE email='$email'");
			if($r['uid']) {
				message('该E-mail已被注册.', $regurl);
			}
			unset($r);
		}
		$password = md5($password);
		$db->query("INSERT INTO {$tablepre}xna_users (username,password, logincount, loginip, logintime, email, url, regtime, regip, groupid) VALUES ('$username','$password', '1', '$onlineip', '$timestamp', '$email', '$url', '$timestamp', '$onlineip', '3')");
		$uid = $db->insert_id();
		$db->query("UPDATE {$tablepre}xna_statistics SET user_count=user_count+1");
		setcookie('sax_auth', authcode("$uid\t$password\t1"), $timestamp+2592000);
		require_once(_ROOT.'include/cache.inc.php');
		statistics_recache();
		message('注册成功.', 'myfeeds.php');
	} else {
		//修改资料
		$password_sql = '';
		$oldpassword = md5($_POST['oldpassword']);
		$newpassword = $_POST['newpassword'];
		if ($newpassword) {
			$user = $db->fetch_one_array("SELECT password FROM {$tablepre}xna_users WHERE uid='$ixnauid'");
			if (!$user) {
				message('出错,请尝试重新登陆再进行此操作');
			}
			if ($oldpassword != $user['password']) {
				message('密码无效');
			}
			if(strlen($newpassword) < 6) {
				message('新密码长度不能小于6位');
			}
			if ($newpassword != $confirmpassword) {
				message('请确认输入的新密码一致');
			}
			if (strpos($newpassword,"\n") !== false || strpos($newpassword,"\r") !== false || strpos($newpassword,"\t") !== false) {
				message('密码包含不可接受字符');
			}
			$password_sql = ", password='".md5($newpassword)."'";
		}
		$url = char_cv($url);
		if ($url && isemail($url)) {
			$r = $db->fetch_one_array("SELECT uid FROM {$tablepre}xna_users WHERE email='$email' AND uid!='$ixnauid'");
			if($r['uid']) {
				message('该E-mail已被注册');
			}
			unset($r);
		}
		$db->query("UPDATE {$tablepre}xna_users SET email='$email' $password_sql WHERE uid='$ixnauid'");
		if ($newpassword) {
			setcookie('sax_auth', '');
			setcookie('comment_post_time', '');
			setcookie('search_post_time', '');
			setcookie('comment_username', '');
			setcookie('comment_url', '');
			message('资料已修改成功,您修改了密码,需要重新登陆.', $loginurl);
		} else {
			message('资料已修改成功.', './index?action=profile');
		}
	}
}

//登陆
if($_POST['action'] == 'dologin') {
		$clientcode = $_POST['clientcode'];
		session_start();
		if (!$clientcode || strtolower($clientcode) != strtolower($_SESSION['code'])) {
	    	 unset($_SESSION['code']);
	        message("" . _LANG_1112 . "", $loginurl);
	        return false;
	    }
	// 取值并过滤部分
	$username = char_cv(trim($_POST['username']));
	$password = md5($_POST['password']);
	$userinfo = $db->fetch_one_array("SELECT uid,username,password,logincount,email,groupid FROM {$tablepre}xna_users WHERE username='$username'");
	if($userinfo['uid'] && $userinfo['password'] == $password) {
		$db->query("UPDATE {$tablepre}xna_users SET logincount=logincount+1, logintime='$timestamp', loginip='$onlineip' WHERE uid='".$userinfo['uid']."'");
		$logincount = $userinfo['logincount']+1;
		setcookie('ixnaauth', authcode("$userinfo[uid]\t$password\t$logincount"), $timestamp+2592000);
		$ixnauid = $userinfo['uid'];
		$ixnauser = addslashes($userinfo['username']);
		message('登陆成功', 'myfeeds.php');
	} else {
		message('登陆失败,请检查您输入的用户名和密码', $loginurl);
	}
}

//找回密码
if($_POST['action'] == 'dolosepwd') {
	class getRandstrClass	{
	    function getCode ()
	     {
	     $str = 'abcdefghijklmnopqrstuvwxyz1234567890';
	     $randString = '';
	     $len = strlen($str)-1;
		 $length = 8;
	     for($i = 0;$i < $length;$i ++){
	           $num = mt_rand(0, $len);
	           $randString .= $str[$num];
	       }
	     return $randString ;
	     }
	 }
	if ($options['seccode']) {
		$clientcode = $_POST['clientcode'];
		session_start();
		if (!$clientcode || strtolower($clientcode) != strtolower($_SESSION['code'])) {
			unset($_SESSION['code']);
			message('验证码错误,请返回重新输入.', './index.php?action=losepwd');
		}
	}
	$query=$db->query("SELECT uid,email FROM {$tablepre}xna_users WHERE username='$username' and email='$email' limit 1 ");
	if (!$db->num($query)){
		message('用户名和信箱不匹配,请检查您输入的用户名和信箱地址', './index.php?action=losepwd');
	}else{
		 	$code = new getRandstrClass();  
 			$str = $code->getCode();
 			$md5str = md5($str);
 			
			include("include/phpmailer.inc.php");
			include("include/smtp.inc.php");			
			$mail=new PHPMailer();			
			$mail->IsSMTP();
			$mail->SMTPAuth  = true;                  // enable SMTP authentication
			$mail->SMTPSecure = "";                // sets the prefix to the servier
			$mail->Host      = "mail.tiplayer.com ";      // sets GMAIL as the SMTP server
			$mail->Port      = 25;                  // set the SMTP port 			
			$mail->Username  = "welcome@tiplayer.com"; 
			$mail->Password  = "";	
			$mail->From      = "welcome@tiplayer.com";
			$mail->FromName  = "iXNA.Net";
			$mail->Subject    = "你在iXNA.Net上的用户名和密码";
			$mail->AltBody    = "Hi,你在iXNA.Net上的用户名".$username."和密码".$str.""; //Text Body			
			$mail->WordWrap  = 50; 
			$mail->AddAddress("".$email."","".$username."");
			$mail->IsHTML(true); 			
			    if(!$mail->Send()) {
			      echo "Mailer Error: " . $mail->ErrorInfo;
			    } else{
			    	$db->query("UPDATE {$tablepre}xna_users SET password='$md5str' WHERE username='".$username."'");
			    	}
		message('请检查您输入和信箱地址,查收密码', './index.php?action=losepwd');
	}
}
//清除cookie
if ($_GET['action'] == 'clearcookies') {
	if(is_array($_COOKIE)) {
		foreach ($_COOKIE as $key => $val) {
			setcookie($key, '');
		}
	}
	message('清除COOKIE成功', './');
}
//添加评论
if($_POST['action'] == 'addcomment') {
	$cookietime = $timestamp+2592000;
	$feedid = intval($_POST['feedid']);
	$username = trim($_POST['username']);
	$password = $_POST['password'];
	$url = trim($_POST['url']);
	$uid = trim($_POST['uid']);
	$content = addslashes(trim($_POST['content']));
	//把评论内容保存到cookie里以免丢失
	setcookie('cmcontent', $content, $cookietime);

	if (!$feedid) {
		message('缺少必要参数', './');
	}

	//禁止IP	
	if ($options['banip_enable'] && $options['ban_ip']) {
		$options['ban_ip'] = str_replace('，', ',', $options['ban_ip']);
		$ban_ips = explode(',', $options['ban_ip']);
		if (is_array($ban_ips) && count($ban_ips)) {
			foreach ($ban_ips AS $ban_ip) {
				$ban_ip = str_replace( '\*', '.*', preg_quote($ban_ip, "/") );
				if (preg_match("/^$ban_ip/", $onlineip)) {
					message('您的IP已经被系统禁止发表评论.', getarticleurl($feedid, $uid, $page));
				}
			}
		}
	}

	if ($options['seccode'] && $ixnagroup != 1 && $ixnagroup !=2 && $ixnagroup !=3) {
		$clientcode = $_POST['clientcode'];
		session_start();
		if (!$clientcode || strtolower($clientcode) != strtolower($_SESSION['code'])) {
			unset($_SESSION['code']);
			message('验证码错误,请返回重新输入.', getarticleurl($feedid, $uid, $page));
		}
	}

	//如果没有登陆
	if (!$ixnauid) {
		if(!$username || strlen($username) > 30) {
			message('用户名为空或用户名太长.', getarticleurl($feedid, $uid, $page).'#addcomment');
		}
		$name_key = array("\\",'&',' ',"'",'"','/','*',',','<','>',"\r","\t","\n",'#','$','(',')','%','@','+','?',';','^');
		foreach($name_key as $value){
			if (strpos($username,$value) !== false){ 
				message('此用户名包含不可接受字符或被管理员屏蔽,请选择其它用户名.', getarticleurl($feedid, $uid, $page).'#addcomment');
			}
		}
		$username = char_cv($username);
		//用户名和密码都非
		if ($username && $password) {
			$user = $db->fetch_one_array("SELECT uid,username,password,logincount,url FROM {$tablepre}xna_users WHERE username='$username'");
			$password = md5($_POST['password']);
			if($user['uid'] && $user['password'] == $password) {
				$db->query("UPDATE {$tablepre}xna_users SET logincount=logincount+1, logintime='$timestamp', loginip='$onlineip' WHERE uid='".$user['uid']."'");
				$logincount = $user['logincount']+1;
				setcookie('sax_auth', authcode("$user[uid]\t$password\t$logincount"), $cookietime);
				//自动读取作者资料
				$ixnauid = $user['uid'];
				$username = addslashes($user['username']);
				$url = addslashes($user['url']);
			} else {
				message('验证失败,请登陆后再发表或重新输入正确的用户名和密码.', getarticleurl($feedid, $uid, $page).'#addcomment');
			}
		//如果只有用户名没有密码
		} elseif ($username && !$password) {
			if ($options['censoruser']) {
				$options['censoruser'] = str_replace('，', ',', $options['censoruser']);
				$banname=explode(',',$options['censoruser']);				
				foreach($banname as $value){
					if (strpos($username,$value) !== false && !$db->fetch_one_array("SELECT uid FROM {$tablepre}xna_users WHERE username='$username'")){
						message('此用户名包含不可接受字符或被管理员屏蔽.您不能使用这个用户名发表评论.', getarticleurl($feedid, $uid, $page).'#addcomment');
					}
				}
			}
			$r = $db->fetch_one_array("SELECT uid FROM {$tablepre}xna_users WHERE username='$username'");
			if($r['uid']) {
				message('该用户名已存在,如果是您注册的,请先登陆.', getarticleurl($feedid, $uid, $page).'#addcomment');
			}
			unset($r);
			//把用户名和URL信息保存到cookie
			setcookie('comment_username',$username,$cookietime);
			setcookie('comment_url',$url,$cookietime);
			$url = char_cv($url);
		}
	} else {
		//如果已登陆
		$user = $db->fetch_one_array("SELECT uid,username,logincount,groupid,password,url FROM {$tablepre}xna_users WHERE uid='$ixnauid'");
		if ($user['uid'] && $user['password'] == $ixnapw && $user['logincount'] == $logincount && $user['groupid'] == $ixnagroup) {
			$ixnauser = addslashes($user['username']);
		} else {			
			message('读取用户信息出错,请重新登陆.', $loginurl);
		}
	}
	
	// 检查限制选项
	if ($options['audit_comment']) {
		$spam = TRUE;
	} elseif ($options['spam_enable']) {
		//链接次数
		if (substr_count($content, 'http://') >= $options['spam_url_num']) {
			$spam = TRUE;
		}
		//禁止词语
		if ($options['spam_words']) {
			$options['spam_words'] = str_replace('，', ',', $options['spam_words']);
			$badwords = explode(',', $options['spam_words']);
			if (is_array($badwords) && count($badwords) ) {
				foreach ($badwords AS $n) {
					if ($n) {
						if (preg_match( "/".preg_quote($n, '/' )."/i", $content)) {
							$spam = TRUE;
							break;
						}
					}
				}
			}
		}
		//内容长度
		if (strlen($content) >= $options['spam_content_size']) {
			$spam = TRUE;
		}
	} else {
		$spam = FALSE;
	}

	$state = $spam ? '0' : '1';
	
	if ($ixnagroup != 1 && $ixnagroup != 2) {
		$lastposttime = $user['lastpost'] ? $user['lastpost'] : $_COOKIE['comment_post_time'];
		if ($options['comment_post_space'] && $timestamp - $lastposttime <= $options['comment_post_space'] && $ixnagroup != 1){
			message('为防止灌水,发表评论时间间隔为'.$options['comment_post_space'].'秒.', getarticleurl($feedid, $uid, $page).'#addcomment');
		}
	}
	$article = $db->fetch_one_array("SELECT closecomment FROM {$tablepre}articles WHERE feedid='$feedid'");
	if ($article['closecomment']) {
		message('本文因为某种原因此时不允许访客进行评论.', getarticleurl($feedid, $uid, $page));
	}
	$result  = '';
	$result .= checkurl($url);
	$result .= checkcontent($content);
	if($result){
		message($result, getarticleurl($feedid, $uid, $page).'#addcomment');
	}
    $r = $db->fetch_one_array("SELECT commentid FROM {$tablepre}comments WHERE feedid='$feedid' AND author='$username' AND content='$content'");
    if($r['commentid']) {
		message('该评论已存在.', getarticleurl($feedid, $uid, $page));
	}
	unset($r);
    $db->query("INSERT INTO {$tablepre}xna_comment (feedid, uid,author, url, addtime, content, ipaddress, state) VALUES ('$feedid', '$uid', '$username', '$url', '$timestamp', '$content', '$onlineip', '$state')");
	$cmid = $db->insert_id();
	if ($ixnauid) {
		$db->query("UPDATE {$tablepre}xna_users SET lastpost='$timestamp' WHERE uid='$ixnauid'");
		// 更新用户最后发表时间
	}
	if (!$spam) {
		// 如果不是垃圾则更新当前文章评论数
		$db->query("UPDATE {$tablepre}articles SET comments=comments+1 WHERE feedid='$feedid'");
		$db->query("UPDATE {$tablepre}space SET comment_count=comment_count+1 WHERE uid='$uid'");
		require_once(_ROOT.'include/cache.inc.php');
		newcomments_recache();
		statistics_recache();
	}
	setcookie('comment_post_time',$timestamp);
	// 跳转到最新发表的评论
	$cmnum = '#cm'.$cmid;
	$article_comment_num = intval($options['article_comment_num']);
	if ($article_comment_num) {
		$cpost = $db->fetch_one_array("SELECT COUNT(*) as comment FROM {$tablepre}xna_comment WHERE feedid='$feedid' AND state='1' AND commentid<='$cmid'");
		if (($cpost['comment'] / $article_comment_num) <= 1 ) {
			$page = 1;
		} else {
			$page = @ceil(($cpost['comment']) / $article_comment_num);
		}
	} else {
		$page = 1;
	}
	if ($spam) {
		message('添加评论成功,目前发表评论需要管理员审核才会显示,请耐心等待管理员审核.', getarticleurl($feedid, $uid, $page));
	}
	setcookie('cmcontent','');
	if ($options['comment_order']) { //新评论靠后排序
		if ($options['showmsg']) {
			message('添加评论成功,返回即可看到您所发表的评论.', getarticleurl($feedid, $uid, $page).$cmnum);
		} else {
			@header('Location: '.getarticleurl($feedid, $uid, $page).$cmnum);
		}
	} else {
		if ($options['showmsg']) {
			message('添加评论成功,返回即可看到您所发表的评论.', getarticleurl($feedid, $uid, $page).'#comment');
		} else {
			@header('Location: '.getarticleurl($feedid, $uid, $page).'#comment');
		}
	}
}
?>